import { Request, Response } from 'express';
import { asyncHandler, ApiError } from '../middlewares/errorHandler';
import prisma from '../config/database';

// 创建订单
export const createOrder = asyncHandler(async (req: Request, res: Response) => {
  const userId = req.user!.userId;
  const { courseId } = req.body;

  // 检查课程是否存在
  const course = await prisma.course.findUnique({
    where: { id: courseId },
  });

  if (!course) {
    throw new ApiError(404, 'Course not found');
  }

  // 检查是否已购买
  const existingOrder = await prisma.order.findFirst({
    where: {
      userId,
      courseId,
      status: 'PAID',
    },
  });

  if (existingOrder) {
    throw new ApiError(400, 'Course already purchased');
  }

  // 生成订单号
  const orderNo = 'ORD' + Date.now() + Math.random().toString(36).substring(2, 9).toUpperCase();

  // 创建订单
  const order = await prisma.order.create({
    data: {
      orderNo,
      userId,
      courseId,
      amount: course.price,
      status: 'PENDING',
    },
  });

  res.status(201).json({
    code: 201,
    message: 'Order created successfully',
    data: order,
  });
});

// 获取我的订单
export const getMyOrders = asyncHandler(async (req: Request, res: Response) => {
  const userId = req.user!.userId;

  const orders = await prisma.order.findMany({
    where: { userId },
    include: {
      course: {
        select: {
          id: true,
          title: true,
          cover: true,
          price: true,
        },
      },
    },
    orderBy: {
      createdAt: 'desc',
    },
  });

  res.json({
    code: 200,
    message: 'Success',
    data: orders,
  });
});

// 获取订单详情
export const getOrderById = asyncHandler(async (req: Request, res: Response) => {
  const { id } = req.params;
  const userId = req.user!.userId;

  const order = await prisma.order.findFirst({
    where: {
      id,
      userId,
    },
    include: {
      course: true,
    },
  });

  if (!order) {
    throw new ApiError(404, 'Order not found');
  }

  res.json({
    code: 200,
    message: 'Success',
    data: order,
  });
});

// 处理支付回调(示例,实际需要根据支付平台具体实现)
export const handlePaymentCallback = asyncHandler(async (req: Request, res: Response) => {
  const { orderNo, transactionId, paymentMethod } = req.body;

  // 验证支付信息(实际应该调用支付平台API验证)

  // 更新订单状态
  const order = await prisma.order.update({
    where: { orderNo },
    data: {
      status: 'PAID',
      paymentMethod,
      transactionId,
      paidAt: new Date(),
    },
  });

  // 自动报名课程
  await prisma.enrollment.create({
    data: {
      userId: order.userId,
      courseId: order.courseId,
    },
  });

  // 更新课程学生数
  await prisma.course.update({
    where: { id: order.courseId },
    data: {
      studentCount: {
        increment: 1,
      },
    },
  });

  res.json({
    code: 200,
    message: 'Payment processed successfully',
    data: order,
  });
});
